package io.web.gateway.filter;

import io.web.gateway.utils.ResponseHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * AccessGlobalFilter.
 * 访问控制
 *
 * @date 2023-05-30
 */
@Component
@Slf4j
public class AccessGlobalFilter implements GlobalFilter, Ordered {

    private static final List<String> IP_WHITE_LIST = Arrays.asList("127.0.0.1", "localhost");

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String hostName = Objects.requireNonNull(exchange.getRequest().getLocalAddress()).getHostName();
        log.info("hostName = {}", hostName);
        // 白名单
        if(!IP_WHITE_LIST.contains(hostName)){
            return ResponseHandler.forbidden(exchange);
        }
        return chain.filter(exchange);
    }


    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE + 100;
    }
}
